<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存结算管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
        .settlement-table th {
            background-color: #f8f9fa;
            position: sticky;
            top: 0;
            font-size: 12px;
            padding: 8px;
        }
        .settlement-table td {
            font-size: 12px;
            padding: 8px;
        }
        .cost-input {
            max-width: 100px;
            font-size: 12px;
        }
        .table-responsive {
            max-height: 70vh;
            overflow-y: auto;
        }
        .form-select {
            font-size: 12px;
        }
        .form-control {
            font-size: 12px;
        }
        .btn-sm {
            font-size: 11px;
            padding: 4px 8px;
        }
        .unpaid-amount {
            font-weight: bold;
            color: #dc3545; /* 红色突出显示 */
        }
        .paid-amount {
            color: #28a745; /* 绿色显示已支付或0金额 */
        }

        /* 移动版样式 */
        .mobile-cards {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
            margin-bottom: 20px;
            display: none;
        }
        .mobile-header {
            background-color: #c0a36c;
            color: white;
            padding: 15px 20px;
        }
        .stock-card {
            padding: 15px;
            border-bottom: 2px solid #e0e0e0;
            cursor: pointer;
            margin-bottom: 12px;
            border-radius: 8px;
            background-color: #ffffff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stock-card:last-child {
            border-bottom: 2px solid #e0e0e0;
            margin-bottom: 0;
        }
        .stock-card:hover {
            background-color: #f5f5f5;
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
        .stock-card.expanded {
            background-color: #f0f8ff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .card-main-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .card-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
        }
        .card-basic-info {
            flex: 1;
        }
        .card-stock-id {
            font-weight: 600;
            font-size: 10px;
            color: #333;
        }
        .card-product-name {
            font-size: 14px;
            color: #666;
        }
        .card-status-group {
            display: grid;
            grid-template-columns: repeat(2, 1fr); /* 固定为2列 */
            gap: 4px;
            width: 120px; /* 固定宽度确保每行显示2个状态 */
            margin-top: 8px; /* 增加与上方内容的间距 */
        }
        .card-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            min-width: 40px;
            text-align: center;
            display: inline-block;
            box-sizing: border-box;
            width: 100%; /* 确保每个状态标签占满网格单元格 */
        }
        .card-details {
            display: none;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .card-detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 14px;
        }
        .card-detail-label {
            color: #666;
            min-width: 100px;
        }
        .card-detail-value {
            color: #333;
            text-align: right;
        }
        .card-action {
            margin-top: 10px;
            text-align: center;
        }
        .mobile-action-btn {
            background-color: #c0a36c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            width: 100%;
        }
        .mobile-action-btn.disabled {
            background-color: #cccccc;
            color: #666666;
            cursor: not-allowed;
            opacity: 0.6;
        }
        .mobile-action-btn.disabled:hover {
            background-color: #cccccc;
        }

        /* 响应式媒体查询 */
        @media (max-width: 768px) {
            .table-responsive {
                display: none;
            }
            .mobile-cards {
                display: block;
            }
            .container-fluid {
                padding: 10px;
            }
            .card {
                margin-bottom: 15px;
            }
            .card-body {
                padding: 15px;
            }
        }
        @media (min-width: 769px) {
            .mobile-cards {
                display: none;
            }
            .table-responsive {
                display: block;
            }
        }
    </style>
</head>
<body>
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div class="container-fluid py-2">
        <div class="row">
            <div class="col">
                <a href="/ej_index" class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-arrow-left"></i> 返回主菜单
                </a>
            </div>
        </div>
    </div>

    <div class="container-fluid py-4">
        <div class="row mb-4">
            <div class="col">
                <h1 class="h3 mb-0">库存结算管理</h1>
                <p class="text-muted">查看和更新库存结算信息</p>
            </div>
        </div>

        <!-- 汇总信息卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">未支付金额汇总</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">材料未支付总额</h6>
                                <h4 class="text-danger" id="totalMaterialUnpaid">¥0.00</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">手工未支付总额</h6>
                                <h4 class="text-danger" id="totalManualUnpaid">¥0.00</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">运输未支付总额</h6>
                                <h4 class="text-danger" id="totalTransferUnpaid">¥0.00</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">其他未支付总额</h6>
                                <h4 class="text-danger" id="totalOtherUnpaid">¥0.00</h4>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card bg-warning text-white">
                            <div class="card-body text-center">
                                <h5 class="card-title">总计未支付金额</h5>
                                <h3 id="totalAllUnpaid">¥0.00</h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 产品筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-3">
                        <label class="form-label">按产品ID筛选</label>
                        <select class="form-select" id="productFilter">
                            <option value="">全部产品</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" id="showSettlementOnly">
                            <label class="form-check-label" for="showSettlementOnly">
                                仅显示需要结算数据
                            </label>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button class="btn btn-secondary w-100" id="showAllBtn">查看全部</button>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button class="btn btn-primary w-100" id="batchSettleBtn" disabled>一起结算</button>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button class="btn btn-info w-100" id="exportSettlementBtn" disabled>导出结算表</button>
                    </div>
                </div>
                <!-- 已选择记录计数显示 -->
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="alert alert-info py-2 mb-0" id="selectedCountAlert" style="display: none;">
                            <i class="bi bi-check-circle"></i> 已选择 <span id="selectedCount">0</span> 条记录
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover settlement-table">
                        <thead>
                            <tr>
                                <th width="50px">
                                    <input type="checkbox" id="selectAll" class="form-check-input">
                                </th>
                                <th width="60px">序号</th>
                                <th>库存编号</th>
                                <th>库存名称</th>
                                <th>产品ID</th>
                                <th>产品名称</th>
                                <th>产品图片</th>
                                <th>材料成本</th>
                                <th>材料未支付金额</th>
                                <th>材料垫支人</th>
                                <th>手工成本</th>
                                <th>手工未支付金额</th>
                                <th>手工垫支人</th>
                                <th>运输成本</th>
                                <th>运输未支付金额</th>
                                <th>运输垫支人</th>
                                <th>其他成本</th>
                                <th>其他未支付金额</th>
                                <th>其他垫支人</th>
                                <th>结算状态</th>
                                <th>最后结算日</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="settlementTableBody">
                            <!-- 数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 移动版卡片容器 -->
        <div id="mobileCards" class="mobile-cards" style="display: none;">
            <div class="mobile-header">
                <h5 style="margin: 0;">库存结算数据列表</h5>
            </div>
            <div id="mobileCardsBody">
                <!-- 移动版卡片将通过JavaScript动态填充 -->
            </div>
        </div>
    </div>

    <!-- 结算模态框 -->
    <div class="modal fade" id="settlementModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">更新结算信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="settlementForm">
                        <input type="hidden" id="modalStockId">
                        <input type="hidden" id="modalSettlementType">
                        <input type="hidden" id="modalInitialBalance">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">库存编号</label>
                                <input type="text" class="form-control" id="modalStockIdDisplay" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">结算类型</label>
                                <select class="form-select" id="modalSettlementTypeSelect" required>
                                    <option value="">请选择结算类型</option>
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">支付金额</label>
                                <input type="number" class="form-control" id="modalPaymentAmount" step="0.01" min="0" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">支付人</label>
                                <select class="form-select" id="modalPayer" required>
                                    <option value="晓" selected>晓</option>
                                    <option value="骆">骆</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" id="modalComment" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveSettlementBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 产品图片模态框 -->
    <div class="modal fade" id="productImageModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">产品图片</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <div id="productImageContainer">
                        <img id="productImageDisplay" 
                             class="img-fluid" 
                             style="max-width: 100%; max-height: 70vh; object-fit: contain;"
                             alt="产品图片">
                    </div>
                    <div id="productImageInfo" class="mt-3">
                        <p class="text-muted mb-1">产品ID: <span id="productIdDisplay"></span></p>
                    </div>
                    <div id="productImageError" class="alert alert-warning" style="display: none;">
                        <i class="bi bi-exclamation-triangle"></i> 无法加载产品图片
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 导出结算表模态框 -->
    <div class="modal fade" id="exportSettlementModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">结算表汇总</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th width="60px">序号</th>
                                    <th>库存编号</th>
                                    <th>产品图片</th>
                                    <th>材料成本</th>
                                    <th>手工成本</th>
                                    <th>运输成本</th>
                                    <th>其他成本</th>
                                    <th>总成本</th>
                                </tr>
                            </thead>
                            <tbody id="exportTableBody">
                                <!-- 汇总数据将通过JavaScript动态填充 -->
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="mt-4">
                        <h6>按垫支人汇总：</h6>
                        <div id="payerSummary" class="bg-light p-3 rounded">
                            <!-- 垫支人汇总数据将通过JavaScript动态填充 -->
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/ejj_functions.js"></script>
    <script>
        // 完全禁用所有自动添加的点击功能，确保库存名称和产品ID都保持纯文本
        function makeProductIdsClickable(selector) {
            // 空函数，不执行任何操作，确保所有文本保持纯文本
            console.log('点击功能已禁用，所有文本保持纯文本显示');
        }

        // 页面加载完成后，确保所有文本保持纯文本
        document.addEventListener('DOMContentLoaded', function() {
            // 确保所有表格单元格都保持纯文本样式
            const allCells = document.querySelectorAll('td');
            allCells.forEach(cell => {
                cell.style.cursor = 'default';
                cell.style.color = '';
                cell.style.textDecoration = '';
                cell.title = '';
                cell.onclick = null;
            });
        });

        let settlementData = [];

        // 检测是否为移动设备
        function isMobileDevice() {
            return window.innerWidth <= 768;
        }

        // 根据设备类型显示正确的视图
        function toggleViewBasedOnDevice() {
            const isMobile = isMobileDevice();
            const pcTable = document.querySelector('.table-responsive');
            const mobileCards = document.getElementById('mobileCards');
            
            if (isMobile) {
                pcTable.style.display = 'none';
                mobileCards.style.display = 'block';
            } else {
                pcTable.style.display = 'block';
                mobileCards.style.display = 'none';
            }
        }

        // 页面加载时获取结算数据
        document.addEventListener('DOMContentLoaded', function() {
            // 初始显示正确的视图
            toggleViewBasedOnDevice();
            
            // 监听窗口大小变化
            window.addEventListener('resize', toggleViewBasedOnDevice);
            
            fetchSettlementData();
        });

        // 获取结算数据
        async function fetchSettlementData() {
            try {
                const response = await fetch('/get_settlement_data');
                const result = await response.json();
                
                if (result.success) {
                    settlementData = result.data;
                    renderSettlementTable(settlementData);
                } else {
                    alert('获取结算数据失败: ' + result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('获取结算数据时发生错误');
            }
        }

        // 渲染结算表格 - 按库存编号归并数据
        function renderSettlementTable(data) {
            const tbody = document.getElementById('settlementTableBody');
            tbody.innerHTML = '';

            // 按库存编号分组数据
            const groupedData = {};
            data.forEach(item => {
                if (!groupedData[item.stock_id]) {
                    groupedData[item.stock_id] = {
                        stock_id: item.stock_id,
                        stock_name: item.stock_name,
                        product_id: item.product_id,
                        product_name: item.product_name,
                        material_amount: 0,
                        material_settled: 0,
                        material_payer: '',
                        material_status: 'pending',
                        manual_amount: 0,
                        manual_settled: 0,
                        manual_payer: '',
                        manual_status: 'pending',
                        transfer_amount: 0,
                        transfer_settled: 0,
                        transfer_payer: '',
                        transfer_status: 'pending',
                        other_amount: 0,
                        other_settled: 0,
                        other_payer: '',
                        other_status: 'pending'
                    };
                }

                // 根据结算类型设置金额和状态
                if (item.settlement_type === 'material') {
                    groupedData[item.stock_id].material_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].material_settled = parseFloat(item.settled_amount || 0);
                    groupedData[item.stock_id].material_payer = item.advance_payer || '';
                    groupedData[item.stock_id].material_status = item.settlement_status || 'pending';
                    groupedData[item.stock_id].material_updated_at = item.settlement_date || '';
                } else if (item.settlement_type === 'manual') {
                    groupedData[item.stock_id].manual_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].manual_settled = parseFloat(item.settled_amount || 0);
                    groupedData[item.stock_id].manual_payer = item.advance_payer || '';
                    groupedData[item.stock_id].manual_status = item.settlement_status || 'pending';
                    groupedData[item.stock_id].manual_updated_at = item.settlement_date || '';
                } else if (item.settlement_type === 'transfer') {
                    groupedData[item.stock_id].transfer_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].transfer_settled = parseFloat(item.settled_amount || 0);
                    groupedData[item.stock_id].transfer_payer = item.advance_payer || '';
                    groupedData[item.stock_id].transfer_status = item.settlement_status || 'pending';
                    groupedData[item.stock_id].transfer_updated_at = item.settlement_date || '';
                } else if (item.settlement_type === 'other') {
                    groupedData[item.stock_id].other_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].other_settled = parseFloat(item.settled_amount || 0);
                    groupedData[item.stock_id].other_payer = item.advance_payer || '';
                    groupedData[item.stock_id].other_status = item.settlement_status || 'pending';
                    groupedData[item.stock_id].other_updated_at = item.settlement_date || '';
                }
            });

            // 计算未支付金额汇总
            let totalMaterialUnpaid = 0;
            let totalManualUnpaid = 0;
            let totalTransferUnpaid = 0;
            let totalOtherUnpaid = 0;

            // 渲染归并后的数据
            let rowNumber = 1; // 初始化序号计数器
            Object.values(groupedData).forEach(item => {
                // 计算各项未支付金额
                const materialUnpaid = item.material_amount - item.material_settled;
                const manualUnpaid = item.manual_amount - item.manual_settled;
                const transferUnpaid = item.transfer_amount - item.transfer_settled;
                const otherUnpaid = item.other_amount - item.other_settled;

                // 累加到总计
                totalMaterialUnpaid += materialUnpaid > 0 ? materialUnpaid : 0;
                totalManualUnpaid += manualUnpaid > 0 ? manualUnpaid : 0;
                totalTransferUnpaid += transferUnpaid > 0 ? transferUnpaid : 0;
                totalOtherUnpaid += otherUnpaid > 0 ? otherUnpaid : 0;

                const row = document.createElement('tr');
                
                // 检查是否有未支付金额大于0的项目
                const hasUnpaidAmount = (materialUnpaid > 0) || (manualUnpaid > 0) || (transferUnpaid > 0) || (otherUnpaid > 0);
                
                row.innerHTML = `
                    <td>
                        <input type="checkbox" class="form-check-input stock-checkbox" 
                               value="${item.stock_id}" 
                               ${!hasUnpaidAmount ? 'disabled' : ''}>
                    </td>
                    <td>${rowNumber}</td>
                    <td>${item.stock_id}</td>
                    <td>${item.stock_name || '-'}</td>
                    <td>${item.product_id}</td>
                    <td>${item.product_name || '-'}</td>
                    <td>
                        ${item.product_id ? 
                            `<img src="/serve_jade_image?product_id=${item.product_id}" 
                                  class="product-image" 
                                  alt="${item.product_name}"
                                  onclick="showJadeImages('${item.product_id}')"
                                  style="cursor: pointer;"
                                  onerror="this.src='/static/images/default_cover.jpg'">` : 
                            '-'}
                    </td>
                    <td>¥${item.material_amount.toFixed(2)}</td>
                    <td class="${(item.material_amount - item.material_settled) > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${(item.material_amount - item.material_settled).toFixed(2)}</td>
                    <td>${item.material_status === 'not_necessary' ? '-' : (item.material_payer || '')}</td>
                    <td>¥${item.manual_amount.toFixed(2)}</td>
                    <td class="${(item.manual_amount - item.manual_settled) > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${(item.manual_amount - item.manual_settled).toFixed(2)}</td>
                    <td>${item.manual_status === 'not_necessary' ? '-' : (item.manual_payer || '')}</td>
                    <td>¥${item.transfer_amount.toFixed(2)}</td>
                    <td class="${(item.transfer_amount - item.transfer_settled) > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${(item.transfer_amount - item.transfer_settled).toFixed(2)}</td>
                    <td>${item.transfer_status === 'not_necessary' ? '-' : (item.transfer_payer || '')}</td>
                    <td>¥${item.other_amount.toFixed(2)}</td>
                    <td class="${(item.other_amount - item.other_settled) > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${(item.other_amount - item.other_settled).toFixed(2)}</td>
                    <td>${item.other_status === 'not_necessary' ? '-' : (item.other_payer || '')}</td>
                    <td>
                        <div class="d-flex flex-column gap-1">
                            <span class="badge ${getStatusBadgeClass(item.material_status)}">材料:${item.material_status}</span>
                            <span class="badge ${getStatusBadgeClass(item.manual_status)}">手工:${item.manual_status}</span>
                            <span class="badge ${getStatusBadgeClass(item.transfer_status)}">运输:${item.transfer_status}</span>
                            <span class="badge ${getStatusBadgeClass(item.other_status)}">其他:${item.other_status}</span>
                        </div>
                    </td>
                    <td>
                        <div class="d-flex flex-column gap-1">
                            <span>${formatDate(item.material_updated_at) || '-'}</span>
                            <span>${formatDate(item.manual_updated_at) || '-'}</span>
                            <span>${formatDate(item.transfer_updated_at) || '-'}</span>
                            <span>${formatDate(item.other_updated_at) || '-'}</span>
                        </div>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-primary update-btn" 
                                data-stock-id="${item.stock_id}"
                                data-bs-toggle="modal" 
                                data-bs-target="#settlementModal"
                                ${shouldDisableSettlementButton(item) ? 'disabled' : ''}>
                            <i class="bi bi-currency-exchange"></i> 结算
                        </button>
                    </td>
                `;

                tbody.appendChild(row);
                rowNumber++; // 增加序号计数器
            });

            // 更新汇总信息
            document.getElementById('totalMaterialUnpaid').textContent = '¥' + totalMaterialUnpaid.toFixed(2);
            document.getElementById('totalManualUnpaid').textContent = '¥' + totalManualUnpaid.toFixed(2);
            document.getElementById('totalTransferUnpaid').textContent = '¥' + totalTransferUnpaid.toFixed(2);
            document.getElementById('totalOtherUnpaid').textContent = '¥' + totalOtherUnpaid.toFixed(2);
            
            const totalAllUnpaid = totalMaterialUnpaid + totalManualUnpaid + totalTransferUnpaid + totalOtherUnpaid;
            document.getElementById('totalAllUnpaid').textContent = '¥' + totalAllUnpaid.toFixed(2);

            // 填充产品筛选下拉框
            populateProductFilter(data);

            // 添加事件监听器
            addEventListeners();
            
            // 渲染移动版卡片
            renderMobileCards(groupedData);
        }

        // 渲染移动版卡片
        function renderMobileCards(groupedData) {
            const cardsBody = document.getElementById('mobileCardsBody');
            cardsBody.innerHTML = '';

            if (Object.keys(groupedData).length === 0) {
                cardsBody.innerHTML = `
                    <div class="stock-card">
                        <div style="text-align: center; padding: 20px; color: #666;">
                            没有找到匹配的库存结算数据
                        </div>
                    </div>
                `;
                return;
            }

            Object.values(groupedData).forEach(item => {
                // 计算各项未支付金额
                const materialUnpaid = item.material_amount - item.material_settled;
                const manualUnpaid = item.manual_amount - item.manual_settled;
                const transferUnpaid = item.transfer_amount - item.transfer_settled;
                const otherUnpaid = item.other_amount - item.other_settled;

                // 检查是否有未支付金额大于0的项目
                const hasUnpaidAmount = (materialUnpaid > 0) || (manualUnpaid > 0) || (transferUnpaid > 0) || (otherUnpaid > 0);
                
                // 检查是否应该禁用结算按钮
                const isDisabled = shouldDisableSettlementButton(item);
                const buttonClass = isDisabled ? 'mobile-action-btn disabled' : 'mobile-action-btn';
                const buttonDisabled = isDisabled ? 'disabled' : '';
                const buttonTitle = isDisabled ? '该记录已结算完毕或无需结算' : '点击进行结算';

                // 生成产品图片HTML - 显示图片并添加点击事件
                const productImageHtml = item.product_id ? 
                    `<img src="/serve_jade_image?product_id=${item.product_id}" 
                          class="card-image"
                          alt="${item.product_name}"
                          onclick="showJadeImages('${item.product_id}')"
                          style="cursor: pointer;"
                          onerror="this.src='/static/images/default_cover.jpg'">` : 
                    '<span style="color: #999; font-size: 12px;">无图片</span>';

                const card = document.createElement('div');
                card.className = 'stock-card';
                card.innerHTML = `
                    <div class="card-header">
                        <div class="card-main-info">
                            <input type="checkbox" class="form-check-input mobile-stock-checkbox" 
                                   value="${item.stock_id}" 
                                   ${!hasUnpaidAmount ? 'disabled' : ''}
                                   style="margin-right: 10px;">
                            ${productImageHtml}
                            <div class="card-basic-info">
                                <div class="card-stock-id">${item.stock_id || '无编号'}</div>
                                <div class="card-product-name">${item.product_name || '无产品名'}</div>
                            </div>
                        </div>
                        <div class="card-status-group">
                            <span class="card-status ${getStatusBadgeClass(item.material_status)}">材料</span>
                            <span class="card-status ${getStatusBadgeClass(item.manual_status)}">手工</span>
                            <span class="card-status ${getStatusBadgeClass(item.transfer_status)}">运输</span>
                            <span class="card-status ${getStatusBadgeClass(item.other_status)}">其他</span>
                        </div>
                    </div>
                    
                    <div class="card-details">
                        <div class="card-detail-row">
                            <span class="card-detail-label">库存名称:</span>
                            <span class="card-detail-value">${item.stock_name || '-'}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">产品ID:</span>
                            <span class="card-detail-value">${item.product_id || '-'}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">材料成本:</span>
                            <span class="card-detail-value">¥${item.material_amount.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">材料未支付:</span>
                            <span class="card-detail-value ${materialUnpaid > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${materialUnpaid.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">手工成本:</span>
                            <span class="card-detail-value">¥${item.manual_amount.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">手工未支付:</span>
                            <span class="card-detail-value ${manualUnpaid > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${manualUnpaid.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">运输成本:</span>
                            <span class="card-detail-value">¥${item.transfer_amount.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">运输未支付:</span>
                            <span class="card-detail-value ${transferUnpaid > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${transferUnpaid.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">其他成本:</span>
                            <span class="card-detail-value">¥${item.other_amount.toFixed(2)}</span>
                        </div>
                        <div class="card-detail-row">
                            <span class="card-detail-label">其他未支付:</span>
                            <span class="card-detail-value ${otherUnpaid > 0 ? 'unpaid-amount' : 'paid-amount'}">¥${otherUnpaid.toFixed(2)}</span>
                        </div>
                        ${item.material_payer ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">材料垫支人:</span>
                            <span class="card-detail-value">${item.material_payer}</span>
                        </div>
                        ` : ''}
                        ${item.manual_payer ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">手工垫支人:</span>
                            <span class="card-detail-value">${item.manual_payer}</span>
                        </div>
                        ` : ''}
                        ${item.transfer_payer ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">运输垫支人:</span>
                            <span class="card-detail-value">${item.transfer_payer}</span>
                        </div>
                        ` : ''}
                        ${item.other_payer ? `
                        <div class="card-detail-row">
                            <span class="card-detail-label">其他垫支人:</span>
                            <span class="card-detail-value">${item.other_payer}</span>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div class="card-action">
                        <button class="${buttonClass}" onclick="${isDisabled ? '' : `openSettlementModal('${item.stock_id}')`}" ${buttonDisabled} title="${buttonTitle}">
                            <i class="bi bi-currency-exchange"></i> 结算
                        </button>
                    </div>
                `;
                
                // 添加点击展开/收起功能
                card.addEventListener('click', function(e) {
                    // 防止点击按钮、图片、复选框或其他交互元素时触发卡片展开
                    if (e.target.tagName === 'BUTTON' || 
                        e.target.tagName === 'IMG' || 
                        e.target.tagName === 'INPUT' ||
                        e.target.closest('.card-basic-info') ||
                        e.target.closest('.card-status-group')) {
                        return;
                    }
                    
                    const details = this.querySelector('.card-details');
                    const isExpanded = details.style.display === 'block';
                    
                    if (isExpanded) {
                        details.style.display = 'none';
                        this.classList.remove('expanded');
                    } else {
                        details.style.display = 'block';
                        this.classList.add('expanded');
                    }
                });
                
                cardsBody.appendChild(card);
            });
        }

        // 获取状态徽章类
        function getStatusBadgeClass(status) {
            switch (status) {
                case 'completed': return 'bg-success';
                case 'partial': return 'bg-warning';
                case 'pending': return 'bg-secondary';
                case 'not_necessary': return 'bg-info';
                default: return 'bg-secondary';
            }
        }

        // 格式化日期函数 - 只显示日期部分
        function formatDate(dateString) {
            if (!dateString) return '';
            
            try {
                const date = new Date(dateString);
                if (isNaN(date.getTime())) return '';
                
                // 格式化为 YYYY-MM-DD
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                
                return `${year}-${month}-${day}`;
            } catch (error) {
                console.error('日期格式化错误:', error);
                return '';
            }
        }

        // 检查是否应该禁用结算按钮
        function shouldDisableSettlementButton(item) {
            // 如果材料、手工、运费、其他4个成本的状态都不包含pending或partial，则禁用结算按钮
            const hasPendingOrPartial = 
                item.material_status === 'pending' || item.material_status === 'partial' ||
                item.manual_status === 'pending' || item.manual_status === 'partial' ||
                item.transfer_status === 'pending' || item.transfer_status === 'partial' ||
                item.other_status === 'pending' || item.other_status === 'partial';
            
            // 如果没有pending或partial状态，则禁用按钮
            return !hasPendingOrPartial;
        }

        // 添加事件监听器
        function addEventListeners() {
            // 结算按钮点击事件
            document.querySelectorAll('.update-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const stockId = this.getAttribute('data-stock-id');
                    openSettlementModal(stockId);
                });
            });

            // 支付金额输入框变化事件
            document.querySelectorAll('.cost-input').forEach(input => {
                input.addEventListener('change', function() {
                    updateSettlementStatus(this);
                });
            });

            // 支付人选择变化事件
            document.querySelectorAll('.form-select').forEach(select => {
                select.addEventListener('change', function() {
                    updateSettlementStatus(this);
                });
            });

            // 结算类型选择变化事件 - 自动填充剩余金额和保存初始余额，并检查是否应该禁用保存按钮
            document.getElementById('modalSettlementTypeSelect')?.addEventListener('change', function() {
                const settlementType = this.value;
                const stockId = document.getElementById('modalStockId').value;
                
                if (settlementType && stockId) {
                    const stockItems = settlementData.filter(d => d.stock_id === stockId);
                    const selectedItem = stockItems.find(item => item.settlement_type === settlementType);
                    
                    if (selectedItem) {
                        const remainingAmount = (parseFloat(selectedItem.amount || 0) - parseFloat(selectedItem.settled_amount || 0)).toFixed(2);
                        document.getElementById('modalPaymentAmount').value = remainingAmount;
                        // 保存当前的余额作为初始余额
                        document.getElementById('modalInitialBalance').value = remainingAmount;
                        
                        // 检查该结算类型是否已经完全结算
                        if (parseFloat(remainingAmount) <= 0) {
                            document.getElementById('saveSettlementBtn').disabled = true;
                            document.getElementById('modalPaymentAmount').disabled = true;
                        } else {
                            document.getElementById('saveSettlementBtn').disabled = false;
                            document.getElementById('modalPaymentAmount').disabled = false;
                        }
                    }
                }
            });

            // 产品筛选下拉框变化事件
            document.getElementById('productFilter')?.addEventListener('change', function() {
                filterByProductId(this.value);
            });

            // 仅显示需要结算数据复选框变化事件
            document.getElementById('showSettlementOnly')?.addEventListener('change', function() {
                filterSettlementOnly(this.checked);
            });

            // 查看全部按钮点击事件
            document.getElementById('showAllBtn')?.addEventListener('click', function() {
                document.getElementById('productFilter').value = '';
                document.getElementById('showSettlementOnly').checked = false;
                filterByProductId('');
                filterSettlementOnly(false);
            });

            // 全选复选框事件
            document.getElementById('selectAll')?.addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.stock-checkbox:not([disabled])');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateBatchSettleButton();
            });

            // 单个复选框事件 - 同时监听PC端和移动端的勾选框
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('stock-checkbox') || e.target.classList.contains('mobile-stock-checkbox')) {
                    updateBatchSettleButton();
                    updateSelectAllState();
                }
            });

            // 一起结算按钮点击事件
            document.getElementById('batchSettleBtn')?.addEventListener('click', function() {
                handleBatchSettle();
            });

            // 导出结算表按钮点击事件
            document.getElementById('exportSettlementBtn')?.addEventListener('click', function() {
                handleExportSettlement();
            });
        }

        // 按产品ID筛选表格
        function filterByProductId(productId) {
            const rows = document.querySelectorAll('#settlementTableBody tr');
            const showSettlementOnly = document.getElementById('showSettlementOnly').checked;
            
            rows.forEach(row => {
                const rowProductId = row.querySelector('td:nth-child(5)').textContent;
                const shouldShowByProduct = !productId || rowProductId === productId;
                
                // 如果同时启用了"仅显示需要结算数据"，需要同时满足两个条件
                if (showSettlementOnly) {
                    const hasPendingOrPartial = checkRowHasPendingOrPartial(row);
                    row.style.display = (shouldShowByProduct && hasPendingOrPartial) ? '' : 'none';
                } else {
                    row.style.display = shouldShowByProduct ? '' : 'none';
                }
            });
        }

        // 仅显示需要结算数据筛选
        function filterSettlementOnly(showOnly) {
            const rows = document.querySelectorAll('#settlementTableBody tr');
            const productId = document.getElementById('productFilter').value;
            
            rows.forEach(row => {
                const rowProductId = row.querySelector('td:nth-child(5)').textContent;
                const shouldShowByProduct = !productId || rowProductId === productId;
                
                if (showOnly) {
                    const hasPendingOrPartial = checkRowHasPendingOrPartial(row);
                    row.style.display = (shouldShowByProduct && hasPendingOrPartial) ? '' : 'none';
                } else {
                    row.style.display = shouldShowByProduct ? '' : 'none';
                }
            });

            // 同时筛选移动版卡片
            filterMobileCardsSettlementOnly(showOnly, productId);
        }

        // 筛选移动版卡片
        function filterMobileCardsSettlementOnly(showOnly, productId) {
            const cards = document.querySelectorAll('.stock-card');
            
            cards.forEach(card => {
                const stockId = card.querySelector('.mobile-stock-checkbox')?.value;
                if (!stockId) return;
                
                // 获取卡片中的产品ID信息
                const productIdElement = card.querySelector('.card-detail-row:nth-child(2) .card-detail-value');
                const cardProductId = productIdElement ? productIdElement.textContent : '';
                
                const shouldShowByProduct = !productId || cardProductId === productId;
                
                if (showOnly) {
                    // 检查卡片是否包含pending或partial状态
                    const hasPendingOrPartial = checkCardHasPendingOrPartial(card);
                    card.style.display = (shouldShowByProduct && hasPendingOrPartial) ? '' : 'none';
                } else {
                    card.style.display = shouldShowByProduct ? '' : 'none';
                }
            });
        }

        // 检查卡片是否包含pending或partial状态
        function checkCardHasPendingOrPartial(card) {
            const statusGroup = card.querySelector('.card-status-group');
            if (!statusGroup) return false;
            
            const statusBadges = statusGroup.querySelectorAll('.card-status');
            for (const badge of statusBadges) {
                const badgeClass = badge.className;
                if (badgeClass.includes('bg-secondary') || badgeClass.includes('bg-warning')) {
                    return true; // pending或partial状态
                }
            }
            return false;
        }

        // 检查行是否包含pending或partial状态
        function checkRowHasPendingOrPartial(row) {
            const statusCell = row.querySelector('td:nth-child(20)'); // 结算状态列
            if (!statusCell) return false;
            
            const statusText = statusCell.textContent;
            return statusText.includes('pending') || statusText.includes('partial');
        }

        // 填充产品筛选下拉框
        function populateProductFilter(data) {
            const productFilter = document.getElementById('productFilter');
            if (!productFilter) return;
            
            // 清空现有选项（保留第一个"全部产品"选项）
            while (productFilter.options.length > 1) {
                productFilter.remove(1);
            }
            
            // 提取去重的产品ID
            const uniqueProductIds = [...new Set(data.map(item => item.product_id))].filter(id => id);
            
            // 按产品ID排序
            uniqueProductIds.sort();
            
            // 添加产品ID选项
            uniqueProductIds.forEach(productId => {
                const option = document.createElement('option');
                option.value = productId;
                option.textContent = productId;
                productFilter.appendChild(option);
            });
        }

        // 打开结算模态框
        function openSettlementModal(stockId) {
            const stockItems = settlementData.filter(d => d.stock_id === stockId);
            if (!stockItems.length) {
                console.log('No stock items found for stockId:', stockId);
                return;
            }

            console.log('Stock items for modal:', stockItems); // 调试信息
            
            // 清除之前的成功消息
            const existingAlerts = document.querySelectorAll('#settlementModal .alert');
            existingAlerts.forEach(alert => alert.remove());
            
            document.getElementById('modalStockId').value = stockId;
            document.getElementById('modalStockIdDisplay').value = stockId;
            
            // 获取结算类型下拉框
            const settlementTypeSelect = document.getElementById('modalSettlementTypeSelect');
            if (!settlementTypeSelect) {
                console.error('Settlement type select element not found');
                return;
            }
            
            // 清空现有选项（保留第一个"请选择结算类型"选项）
            while (settlementTypeSelect.options.length > 1) {
                settlementTypeSelect.remove(1);
            }
            
            // 过滤掉状态为 'not_necessary' 或 'completed' 的结算类型，只保留 'pending' 或 'partial'
            const availableTypes = [];
            stockItems.forEach(item => {
                console.log('Checking item:', item.settlement_type, 'status:', item.settlement_status); // 调试信息
                if (item.settlement_status === 'pending' || item.settlement_status === 'partial') {
                    availableTypes.push(item.settlement_type);
                }
            });
            
            console.log('Available types:', availableTypes); // 调试信息
            
            // 添加可用的结算类型选项
            const typeNames = {
                'material': '材料结算',
                'manual': '手工结算', 
                'transfer': '运输结算',
                'other': '其他结算'
            };
            
            availableTypes.forEach(type => {
                const option = document.createElement('option');
                option.value = type;
                option.textContent = typeNames[type] || type;
                settlementTypeSelect.appendChild(option);
            });
            
            // 如果没有可用的结算类型，禁用下拉框和保存按钮
            if (availableTypes.length === 0) {
                settlementTypeSelect.disabled = true;
                document.getElementById('saveSettlementBtn').disabled = true;
                document.getElementById('modalPaymentAmount').disabled = true;
                document.getElementById('modalPayer').disabled = true;
                console.log('No available settlement types'); // 调试信息
            } else {
                settlementTypeSelect.disabled = false;
                document.getElementById('saveSettlementBtn').disabled = false;
                document.getElementById('modalPaymentAmount').disabled = false;
                document.getElementById('modalPayer').disabled = false;
                console.log('Available settlement types:', availableTypes); // 调试信息
            }
            
            // 重置其他表单字段
            document.getElementById('modalPaymentAmount').value = '';
            document.getElementById('modalPayer').value = '晓';
            document.getElementById('modalComment').value = '';

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('settlementModal'));
            modal.show();
        }

        // 更新结算状态
        function updateSettlementStatus(element) {
            const stockId = element.getAttribute('data-stock-id');
            const type = element.getAttribute('data-type');
            
            // 这里可以添加自动更新结算状态的逻辑
            console.log(`更新结算状态: stockId=${stockId}, type=${type}`);
        }

        // 保存结算信息
        document.getElementById('saveSettlementBtn').addEventListener('click', async function() {
            const stockId = document.getElementById('modalStockId').value;
            const settlementType = document.getElementById('modalSettlementTypeSelect').value;
            const paymentAmount = parseFloat(document.getElementById('modalPaymentAmount').value);
            const initialBalance = parseFloat(document.getElementById('modalInitialBalance').value);
            const payer = document.getElementById('modalPayer').value;
            const comment = document.getElementById('modalComment').value;

            if (!paymentAmount || !payer) {
                alert('请填写完整的支付信息');
                return;
            }

            try {
                const response = await fetch('/update_settlement_stock', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        stock_id: stockId,
                        settlement_type: settlementType,
                        payment_amount: paymentAmount,
                        initial_balance_amount: initialBalance,
                        payer: payer,
                        comment: comment
                    })
                });

                const result = await response.json();
                
                
                if (result.success) {
                    // 在模态框内显示成功消息，不关闭对话框
                    const successMessage = document.createElement('div');
                    successMessage.className = 'alert alert-success mt-3';
                    successMessage.innerHTML = `
                        <i class="bi bi-check-circle"></i> 
                        ${getSettlementTypeName(settlementType)}结算成功
                        <button type="button" class="btn-close float-end" data-bs-dismiss="alert"></button>
                    `;
                    
                    // 移除之前的成功消息（如果有）
                    const existingAlert = document.querySelector('#settlementModal .alert');
                    if (existingAlert) {
                        existingAlert.remove();
                    }
                    
                    // 将成功消息插入到表单底部
                    document.getElementById('settlementForm').appendChild(successMessage);
                    
                    // 检查此次结算后未结算部分是否为0
                    const remainingAmount = initialBalance - paymentAmount;
                    if (remainingAmount <= 0) {
                        // 如果未结算部分为0，禁用保存按钮
                        document.getElementById('saveSettlementBtn').disabled = true;
                        document.getElementById('modalPaymentAmount').disabled = true;
                    }
                    
                    // 刷新数据但不关闭模态框
                    fetchSettlementData();
                } else {
                    alert('更新失败: ' + result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('更新结算信息时发生错误');
            }
        });

        // 获取结算类型的中文名称
        function getSettlementTypeName(type) {
            const typeNames = {
                'material': '材料费',
                'manual': '手工费', 
                'transfer': '运输费',
                'other': '其他费用'
            };
            return typeNames[type] || type;
        }

        // 更新批量结算按钮状态 - 同时检查PC端和移动端的勾选框
        function updateBatchSettleButton() {
            const batchSettleBtn = document.getElementById('batchSettleBtn');
            const exportSettlementBtn = document.getElementById('exportSettlementBtn');
            const selectedPC = document.querySelectorAll('.stock-checkbox:checked:not([disabled])');
            const selectedMobile = document.querySelectorAll('.mobile-stock-checkbox:checked:not([disabled])');
            
            const totalSelected = selectedPC.length + selectedMobile.length;
            const hasSelected = totalSelected > 0;
            
            batchSettleBtn.disabled = !hasSelected;
            exportSettlementBtn.disabled = !hasSelected;
            
            // 更新已选择记录计数显示
            updateSelectedCountDisplay(totalSelected);
        }

        // 更新已选择记录计数显示
        function updateSelectedCountDisplay(count) {
            const countElement = document.getElementById('selectedCount');
            const alertElement = document.getElementById('selectedCountAlert');
            
            countElement.textContent = count;
            
            if (count > 0) {
                alertElement.style.display = 'block';
            } else {
                alertElement.style.display = 'none';
            }
        }

        // 更新全选复选框状态
        function updateSelectAllState() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.stock-checkbox:not([disabled])');
            const checkedCheckboxes = document.querySelectorAll('.stock-checkbox:checked:not([disabled])');
            
            if (checkedCheckboxes.length === 0) {
                selectAll.checked = false;
                selectAll.indeterminate = false;
            } else if (checkedCheckboxes.length === checkboxes.length) {
                selectAll.checked = true;
                selectAll.indeterminate = false;
            } else {
                selectAll.checked = false;
                selectAll.indeterminate = true;
            }
        }

        // 处理批量结算 - 同时处理PC端和移动端的勾选框
        async function handleBatchSettle() {
            const selectedPC = document.querySelectorAll('.stock-checkbox:checked:not([disabled])');
            const selectedMobile = document.querySelectorAll('.mobile-stock-checkbox:checked:not([disabled])');
            
            const totalSelected = selectedPC.length + selectedMobile.length;
            
            if (totalSelected === 0) {
                alert('请选择要结算的库存项目');
                return;
            }

            // 确认对话框
            const confirmMessage = `确定要结算选中的 ${totalSelected} 个库存项目吗？\n系统将自动结算所有未支付金额大于0的项目。`;
            
            if (!confirm(confirmMessage)) {
                return;
            }

            try {
                // 收集选中的库存编号（PC端和移动端）
                const selectedStockIds = [];
                
                // 添加PC端选中的库存编号
                selectedPC.forEach(checkbox => {
                    selectedStockIds.push(checkbox.value);
                });
                
                // 添加移动端选中的库存编号
                selectedMobile.forEach(checkbox => {
                    selectedStockIds.push(checkbox.value);
                });
                
                const response = await fetch('/batch_settle_stocks', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        stock_ids: selectedStockIds,
                        payer: '晓' // 默认支付人
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    alert(`批量结算成功！共结算了 ${result.settled_count} 个项目`);
                    // 刷新页面数据
                    fetchSettlementData();
                } else {
                    alert('批量结算失败: ' + result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('批量结算时发生错误');
            }
        }

        // 显示产品图片函数
        function showProductImage(productId) {
            if (!productId) {
                alert('无效的产品ID');
                return;
            }

            // 设置产品ID显示
            document.getElementById('productIdDisplay').textContent = productId;
            
            // 设置图片源
            const imageDisplay = document.getElementById('productImageDisplay');
            const imageContainer = document.getElementById('productImageContainer');
            const errorDiv = document.getElementById('productImageError');
            
            // 重置状态
            errorDiv.style.display = 'none';
            imageContainer.style.display = 'block';
            
            // 设置图片加载事件
            imageDisplay.onload = function() {
                imageContainer.style.display = 'block';
                errorDiv.style.display = 'none';
            };
            
            imageDisplay.onerror = function() {
                imageContainer.style.display = 'none';
                errorDiv.style.display = 'block';
                // 尝试加载默认图片
                if (this.src.indexOf('default_cover.jpg') === -1) {
                    this.src = '/static/images/default_cover.jpg';
                }
            };
            
            // 设置图片源
            imageDisplay.src = `/serve_jade_image?product_id=${productId}`;
            
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('productImageModal'));
            modal.show();
        }

        // 处理导出结算表
        function handleExportSettlement() {
            const selectedPC = document.querySelectorAll('.stock-checkbox:checked:not([disabled])');
            const selectedMobile = document.querySelectorAll('.mobile-stock-checkbox:checked:not([disabled])');
            
            const totalSelected = selectedPC.length + selectedMobile.length;
            
            if (totalSelected === 0) {
                alert('请选择要导出的库存项目');
                return;
            }

            // 收集选中的库存编号（PC端和移动端）
            const selectedStockIds = [];
            
            // 添加PC端选中的库存编号
            selectedPC.forEach(checkbox => {
                selectedStockIds.push(checkbox.value);
            });
            
            // 添加移动端选中的库存编号
            selectedMobile.forEach(checkbox => {
                selectedStockIds.push(checkbox.value);
            });

            // 获取选中的库存数据
            const selectedData = settlementData.filter(item => selectedStockIds.includes(item.stock_id));
            
            if (selectedData.length === 0) {
                alert('未找到选中的库存数据');
                return;
            }

            // 按库存编号分组数据
            const groupedData = {};
            selectedData.forEach(item => {
                if (!groupedData[item.stock_id]) {
                    groupedData[item.stock_id] = {
                        stock_id: item.stock_id,
                        stock_name: item.stock_name,
                        product_id: item.product_id,
                        product_name: item.product_name,
                        material_amount: 0,
                        material_payer: '',
                        manual_amount: 0,
                        manual_payer: '',
                        transfer_amount: 0,
                        transfer_payer: '',
                        other_amount: 0,
                        other_payer: ''
                    };
                }

                // 根据结算类型设置金额和垫支人
                if (item.settlement_type === 'material') {
                    groupedData[item.stock_id].material_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].material_payer = item.advance_payer || '';
                } else if (item.settlement_type === 'manual') {
                    groupedData[item.stock_id].manual_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].manual_payer = item.advance_payer || '';
                } else if (item.settlement_type === 'transfer') {
                    groupedData[item.stock_id].transfer_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].transfer_payer = item.advance_payer || '';
                } else if (item.settlement_type === 'other') {
                    groupedData[item.stock_id].other_amount = parseFloat(item.amount || 0);
                    groupedData[item.stock_id].other_payer = item.advance_payer || '';
                }
            });

            // 渲染导出表格
            renderExportTable(groupedData);

            // 计算垫支人汇总
            calculatePayerSummary(groupedData);

            // 显示导出模态框
            const modal = new bootstrap.Modal(document.getElementById('exportSettlementModal'));
            modal.show();
        }

        // 渲染导出表格
        function renderExportTable(groupedData) {
            const tbody = document.getElementById('exportTableBody');
            tbody.innerHTML = '';

            let rowNumber = 1;
            Object.values(groupedData).forEach(item => {
                const totalCost = item.material_amount + item.manual_amount + item.transfer_amount + item.other_amount;
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${rowNumber}</td>
                    <td>${item.stock_id}</td>
                    <td>
                        ${item.product_id ? 
                            `<img src="/serve_jade_image?product_id=${item.product_id}" 
                                  class="product-image" 
                                  alt="${item.product_name}"
                                  style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
                                  onerror="this.src='/static/images/default_cover.jpg'">` : 
                            '-'}
                    </td>
                    <td>¥${item.material_amount.toFixed(2)}</td>
                    <td>¥${item.manual_amount.toFixed(2)}</td>
                    <td>¥${item.transfer_amount.toFixed(2)}</td>
                    <td>¥${item.other_amount.toFixed(2)}</td>
                    <td class="fw-bold">¥${totalCost.toFixed(2)}</td>
                `;
                
                tbody.appendChild(row);
                rowNumber++;
            });
        }

        // 计算垫支人汇总
        function calculatePayerSummary(groupedData) {
            const payerSummary = document.getElementById('payerSummary');
            payerSummary.innerHTML = '';

            const payerTotals = {};

            // 动态收集所有垫支人并计算金额汇总
            Object.values(groupedData).forEach(item => {
                // 处理材料垫支人
                if (item.material_payer && item.material_amount > 0) {
                    const payer = item.material_payer;
                    if (!payerTotals[payer]) {
                        payerTotals[payer] = { material: 0, manual: 0, transfer: 0, other: 0, total: 0 };
                    }
                    payerTotals[payer].material += item.material_amount;
                    payerTotals[payer].total += item.material_amount;
                }

                // 处理手工垫支人
                if (item.manual_payer && item.manual_amount > 0) {
                    const payer = item.manual_payer;
                    if (!payerTotals[payer]) {
                        payerTotals[payer] = { material: 0, manual: 0, transfer: 0, other: 0, total: 0 };
                    }
                    payerTotals[payer].manual += item.manual_amount;
                    payerTotals[payer].total += item.manual_amount;
                }

                // 处理运输垫支人
                if (item.transfer_payer && item.transfer_amount > 0) {
                    const payer = item.transfer_payer;
                    if (!payerTotals[payer]) {
                        payerTotals[payer] = { material: 0, manual: 0, transfer: 0, other: 0, total: 0 };
                    }
                    payerTotals[payer].transfer += item.transfer_amount;
                    payerTotals[payer].total += item.transfer_amount;
                }

                // 处理其他垫支人
                if (item.other_payer && item.other_amount > 0) {
                    const payer = item.other_payer;
                    if (!payerTotals[payer]) {
                        payerTotals[payer] = { material: 0, manual: 0, transfer: 0, other: 0, total: 0 };
                    }
                    payerTotals[payer].other += item.other_amount;
                    payerTotals[payer].total += item.other_amount;
                }
            });

            // 如果没有垫支人数据，显示提示信息
            if (Object.keys(payerTotals).length === 0) {
                payerSummary.innerHTML = `
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> 选中的库存项目暂无垫支人信息
                    </div>
                `;
                return;
            }

            // 生成垫支人汇总HTML
            let summaryHtml = '<div class="row">';
            
            Object.entries(payerTotals).forEach(([payer, amounts]) => {
                summaryHtml += `
                    <div class="col-md-6 mb-3">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h6 class="card-title mb-0">${payer} 垫支汇总</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-6">
                                        <small class="text-muted">材料费:</small><br>
                                        <span class="fw-bold">¥${amounts.material.toFixed(2)}</span>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">手工费:</small><br>
                                        <span class="fw-bold">¥${amounts.manual.toFixed(2)}</span>
                                    </div>
                                    <div class="col-6 mt-2">
                                        <small class="text-muted">运输费:</small><br>
                                        <span class="fw-bold">¥${amounts.transfer.toFixed(2)}</span>
                                    </div>
                                    <div class="col-6 mt-2">
                                        <small class="text-muted">其他费:</small><br>
                                        <span class="fw-bold">¥${amounts.other.toFixed(2)}</span>
                                    </div>
                                    <div class="col-12 mt-3 pt-2 border-top">
                                        <small class="text-muted">总计:</small><br>
                                        <span class="fw-bold text-primary fs-5">¥${amounts.total.toFixed(2)}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            summaryHtml += '</div>';
            payerSummary.innerHTML = summaryHtml;
        }
    </script>
</body>
</html>
